<?php

class Paycallback extends BZ_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('alipay/alipaypc', null, 'alipaypc');
        $this->load->library('ccbpay/ccbpay', null, 'ccbpay');
        $this->load->model('pay_failure_log_model', 'pay_failure_log');
        $this->load->model('tourism_goods_attr_model', 'tourism_goods_attr');
        $this->load->model('tourism_order_main_model', 'tourism_order_main');
        $this->load->model('tourism_order_model', 'tourism_order');
        $this->load->model('tourism_order_product_model', 'tourism_order_product');
        $this->load->model('user_account_model', 'user_account');
        
    }

    /*支付宝回调异步在购物车结算 -----拿到的为总订单*/
    public function alipayNotify()
    {
        $response = $this->alipaypc->responseAlipayNotify();
        $order_sn = $response;
        $postdata = $this->input->post();
        if ($response) {
            $resultOrder = $this->tourism_order_main->findByOrderMain($order_sn);
            if ($resultOrder->num_rows() > 0) {
                $orderInfo = $resultOrder->row();
                if ($orderInfo->status == 1) {
                    $this->db->trans_start();
                    $params['order_state'] = 2;
                    $params['order_status'] = 3;
                    $params['pay_time'] = date('Y-m-d H:i:s');
                    $params['pay_bank'] = 1;
                    $this->tourism_order->updateByOrderMainSn($order_sn, $params);
                    $param['status'] = 2;
                    $this->tourism_order_main->updateStatus($order_sn, $param);

                    //更新商品信息
                    $tourismOrder = $this->tourism_order->findTourismGoods($order_sn);
                    foreach ($tourismOrder->result() as $t=>$item) {
                        $product_param['goods_attr_id'] = $item->goods_attr_id;
                        $product_param['number']        = $item->number;
                        $this->tourism_goods_attr->updateTourismSale($product_param);
                    }
                    //提醒供应商发货
                    $tourismOrder = $this->tourism_order->findByOrderMainSn($order_sn);
                    foreach ($tourismOrder->result() as $item) {
                        if (!empty($item->pay_swim)) {  //更新U币
                            $this->user_account->updateUserAccountUb($item->payer_uid, $item->pay_swim);
                        }
                        if (!empty($item->cellphone)) {
                            //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                            $this->sendCommonSmsInfo($item->cellphone, 'SMS_136383536', ['providerName' => $item->user_name]);
                        }
                    }
                    $this->db->trans_complete();
                }
            }
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_sn, $postdata, $response);
            }
        }
    }

   
    
    /**
     * 银联异步调用
     * 异步回调函数，主订单order_main_sn
     */
    public function chinapayNotify()
    {
        $postData = $this->input->post();
        $response = $this->chinapay->responseChinapayApi($postData);
        $order_main_sn = (int)$this->input->post('orderno');
        $resultOrder = $this->tourism_order_main->findByOrderMain($order_main_sn);
        if( $resultOrder->num_rows()<=0 ){
            $this->jsonMessage('订单信息有误，或长时间未支付');
        }
        $orderInfo = $resultOrder->row();
        
        if ($response===true) { //$response付款成功；
            if( $orderInfo->status>1 ){
                $this->jsonMessage('该订单已经支付');
            }
            $this->db->trans_start();
            $params['order_state'] = 2;
            $params['order_status'] = 3;
            $params['pay_time'] = date('Y-m-d H:i:s');
            $params['pay_bank'] = 200;
            $this->tourism_order->updateByOrderMainSn($order_main_sn,$params);
            $param['status'] = 2;
            $this->tourism_order_main->updateStatus($order_main_sn,$param);
            
            //更新商品信息
            $tourismOrder = $this->tourism_order->findTourismGoods($order_main_sn);
            foreach ($tourismOrder->result() as $t=>$item) {
                $product_param['goods_attr_id'] = $item->goods_attr_id;
                $product_param['number'] = $item->number;
                $this->tourism_goods_attr->updateTourismSale($product_param);
            }
            $this->db->trans_complete();
            //提醒供应商发货
            $tourismOrder = $this->tourism_order->findByOrderMainSn($order_main_sn);
            foreach ($tourismOrder->result() as $item) {
                if (!empty($item->pay_swim)) {  //更新U币数量
                    $this->user_account->updateUserAccountUb($item->payer_uid,$item->pay_swim);
                }
                if (!empty($item->cellphone)) {
                    //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                    $this->sendCommonSmsInfo($item->cellphone, 'SMS_136383536', ['providerName' => $item->user_name]);
                }
            }
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_main_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_main_sn, $postData, array('status'=>$response));
            }
        }
    }

    /**
     * 支付宝支付回调函数。
     */
    public function alipayNotifyU()
    {
        $response = $this->alipaypc->responseAlipayNotify();
        $order_sn = $response;
        $postdata = $this->input->post();
        if ($response) {
            //是否支付
            $orderInfo = $this->isExistOrder($order_sn);
            if($orderInfo){
                /*开启事务*/
                $this->db->trans_start();
                $params['order_state'] = 2;
                $params['order_status'] = 3;
                $params['pay_time'] = date('Y-m-d H:i:s');
                $params['pay_bank'] = 1;
                $this->tourism_order->updateStatus($order_sn, $params);
                //更新商品信息
                $product = $this->tourism_order->findTourismGoods($order_sn, true);
                foreach ($product->result() as $item) {
                    $product_param['goods_attr_id'] = $item->goods_attr_id;
                    $product_param['number'] = $item->number;
                    $this->tourism_goods_attr->updateTourismSale($product_param);
                }
                //给供应商发短信，提醒供应商发货
                $tourismOrder = $this->tourism_order->findByOrderId($orderInfo->order_id);
                if( !empty($tourismOrder->pay_swim) ){  //更新U币
                    $this->user_account->updateUserAccountUb($tourismOrder->payer_uid,$tourismOrder->pay_swim);
                }
                if(!empty($tourismOrder->cellphone)){
                    //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                    $this->sendCommonSmsInfo($tourismOrder->cellphone, 'SMS_136383536', ['providerName' => $tourismOrder->user_name]);
                }
                $this->db->trans_complete();
            }
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_sn, $postdata, $response);
            }
        }
    }

    /* 微信jsapi支付回调*/
    public function wxNotify()
    {
        include_once(getcwd()."/application/libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php");
        $notify = new Notify_pub();//使用通用通知接口
//         $xml    = $GLOBALS['HTTP_RAW_POST_DATA'];   //存储微信的回调
        $xml = file_get_contents('php://input', 'r');
        file_put_contents(FCPATH."application/logs/newfile.txt", $xml.'------------'.date('Y-m-d H:i:s').'\n',FILE_APPEND);
        $notify->saveData($xml);
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if( $notify->checkSign() == FALSE ){
            $notify->setReturnParameter("return_code","FAIL");  //返回状态码
            $notify->setReturnParameter("return_msg","签名失败");  //返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;      //echo为微信返回值   不能更改   不能删除

        if($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL" || $notify->data["result_code"] == "FAIL")
            {
                $return_param = "【通信出错】【业务出错】:\n".$xml."\n";
                $result = $this->pay_failure_log->findByOrderSn($notify->data["out_trade_no"]);
                if (!$result) { //保存错误日志。
                    $last_id = $this->pay_failure_log->insertPayFailureLog($notify->data["out_trade_no"], $return_param, "微信支付报错");
                }
            }else{
                $order_sn = $notify->data["out_trade_no"];
                $resultOrder = $this->tourism_order_main->findByOrderMain($order_sn);
                if ($resultOrder->num_rows() > 0) {
                    $orderInfo = $resultOrder->row();
                    if ($orderInfo->status == 1) {
                        $this->db->trans_start();
                        $params['order_state'] = 2;
                        $params['order_status'] = 3;
                        $params['pay_time'] = date('Y-m-d H:i:s');
                        $params['pay_bank'] = 201;
                        $this->tourism_order->updateByOrderMainSn($order_sn,$params);
                        $param['status'] = 2;
                        $this->tourism_order_main->updateStatus($order_sn,$param);
                        //更新商品信息
                        $tourismOrder = $this->tourism_order->findTourismGoods($order_sn);
                        foreach ($tourismOrder->result() as $t=>$item) {
                            $product_param['goods_attr_id'] = $item->goods_attr_id;
                            $product_param['number'] = $item->number;
                            $this->tourism_goods_attr->updateTourismSale($product_param);
                        }
                        //提醒供应商发货
                        $tourismOrder = $this->tourism_order->findByOrderMainSn($order_sn);
                        foreach ($tourismOrder->result() as $item) {
                        	if( !empty($item->pay_swim) ){  //更新U币
                                $this->user_account->updateUserAccountUb($item->payer_uid,$item->pay_swim);
                            }
                            if (!empty($item->cellphone)) {
                                // $item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                                $this->sendCommonSmsInfo($item->cellphone, 'SMS_136383536', ['providerName' => $item->user_name]);
                            }
                        }
                        $this->db->trans_complete();
                    }
                }
            }
        }
    }

    /* 微信jsapi支付回调*/
    public function wxNotifyU()
    {
        include_once(getcwd()."/application/libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php");
        $notify = new Notify_pub();//使用通用通知接口
        $xml    = file_get_contents('php://input', 'r');   //存储微信的回调
        $notify->saveData($xml);

        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if( $notify->checkSign() == FALSE ){
            $notify->setReturnParameter("return_code","FAIL");  //返回状态码
            $notify->setReturnParameter("return_msg","签名失败");  //返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;      //echo为微信返回值   不能更改   不能删除

        if($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL" || $notify->data["result_code"] == "FAIL")
            {
                $return_param = "【通信出错】【业务出错】:\n".$xml."\n";
                $result = $this->pay_failure_log->findByOrderSn($notify->data["out_trade_no"]);
                if (!$result) { //保存错误日志。
                    $last_id = $this->pay_failure_log->insertPayFailureLog($notify->data["out_trade_no"], $return_param, "微信支付报错");
                }
            }else{
                $order_sn = $notify->data["out_trade_no"];
                $orderInfo = $this->isExistOrder($order_sn);
                if($orderInfo){
                    /*开启事务*/
                    $this->db->trans_start();
                    $params['order_state'] = 2;
                    $params['order_status'] = 3;
                    $params['pay_time'] = date('Y-m-d H:i:s');
                    $params['pay_bank'] = 201;
                    $this->tourism_order->updateStatus($order_sn, $params);
                    //更新商品信息
                    $product = $this->tourism_order->findTourismGoods($order_sn, true);
                    foreach ($product->result() as $item) {
                        $product_param['goods_attr_id'] = $item->goods_attr_id;
                        $product_param['number'] = $item->number;
                        $this->tourism_goods_attr->updateTourismSale($product_param);
                    }
                    //给供应商发短信，提醒供应商发货
                    $tourismOrder = $this->tourism_order->findByOrderId($orderInfo->order_id);
                    if( !empty($tourismOrder->pay_swim) ){  //更新U币
                        $this->user_account->updateUserAccountUb($tourismOrder->payer_uid,$tourismOrder->pay_swim);
                    }
                    if (!empty($tourismOrder->cellphone)) {
                        // $item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                        $this->sendCommonSmsInfo($tourismOrder->cellphone, 'SMS_136383536', ['providerName' => $tourismOrder->user_name]);
                    }
                    $this->db->trans_complete();
                }
            }
        }
    }

    /**
     * 建行异步调用
     * 异步回调函数，主订单order_main_sn
     */
    public function ccbpayNotify()
    {
        $response = $this->ccbpay->responseCcbNotify();
        $order_main_sn = $this->input->post('ORDERID', true);
        $resultOrder = $this->tourism_order_main->findByOrderMain($order_main_sn);
        if( $resultOrder->num_rows()<=0 ){
            $this->jsonMessage('订单信息有误，或长时间未支付');
        }
        $orderInfo = $resultOrder->row();
        
        if ($response) { //$response付款成功；
            if( $orderInfo->status>1 ){
                $this->jsonMessage('该订单已经支付');
            }
            $this->db->trans_start();
            $params['order_state'] = 2;
            $params['order_status'] = 3;
            $params['pay_time'] = date('Y-m-d H:i:s');
            $params['pay_bank'] = 210;
            $this->tourism_order->updateByOrderMainSn($order_main_sn,$params);
            $param['status'] = 2;
            $this->tourism_order_main->updateStatus($order_main_sn,$param);
            
            //更新商品信息
            $tourismOrder = $this->tourism_order->findTourismGoods($order_main_sn);
            foreach ($tourismOrder->result() as $t=>$item) {
                $product_param['goods_attr_id'] = $item->goods_attr_id;
                $product_param['number'] = $item->number;
                $this->tourism_goods_attr->updateTourismSale($product_param);
            }
            $this->db->trans_complete();
            //提醒供应商发货
            $tourismOrder = $this->tourism_order->findByOrderMainSn($order_main_sn);
            foreach ($tourismOrder->result() as $item) {
                if( !empty($item->pay_swim) ){  //更新U币数量
                    $this->user_account->updateUserAccountUb($item->payer_uid,$item->pay_swim);
                }
                if (!empty($item->cellphone)) {
                    //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                    $this->sendCommonSmsInfo($item->cellphone, 'SMS_136383536', ['providerName' => $item->user_name]);
                }
            }
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_main_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_main_sn, $this->input->post(), array('status'=>$this->ccbpay->getMessage()));
            }
        }
    }

    /**
     * 建行异步调用
     * 个人中心小订单支付
     */
    public function ccbpayNotifyU()
    {
        $response = $this->ccbpay->responseCcbNotify();
        $order_sn = $this->input->post('ORDERID', true);
        $result = $this->tourism_order->findByOrderSn($order_sn);
        if ($result->num_rows() <= 0) {
            $this->jsonMessage('订单信息有误，或长时间未支付');
        }
        $orderInfo = $result->row();
        if($orderInfo->order_state != 1 && $orderInfo->order_status != 2){
            $this->jsonMessage('该订单已经支付');
        }
        if($response){ // 支付成功
            /*开启事务*/
            $this->db->trans_start();
            $params['order_state'] = 2;
            $params['order_status'] = 3;
            $params['pay_time'] = date('Y-m-d H:i:s');
            $params['pay_bank'] = 210;
            $this->tourism_order->updateStatus($order_sn, $params);
            //更新商品信息
            $product = $this->tourism_order->findTourismGoods($order_sn, true);
            foreach ($product->result() as $item) {
                $product_param['goods_attr_id'] = $item->goods_attr_id;
                $product_param['number'] = $item->number;
                $this->tourism_goods_attr->updateTourismSale($product_param);
            }
            //给供应商发短信，提醒供应商发货
            $tourismOrder = $this->tourism_order->findByOrderId($orderInfo->order_id);
            if( !empty($tourismOrder->pay_swim) ){  //更新U币
                $this->user_account->updateUserAccountUb($tourismOrder->payer_uid,$tourismOrder->pay_swim);
            }
            if (!empty($tourismOrder->cellphone)) {
                //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                $this->sendCommonSmsInfo($tourismOrder->cellphone, 'SMS_136383536', ['providerName' => $tourismOrder->user_name]);
            }
            $this->db->trans_complete();
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_sn, $this->input->post(), $this->ccbpay->getMessage());
            }
        }
    }

     /**
     * 个人中心小订单支付
     */
    public function chinapayNotifyU()
    {
        $postData = $this->input->post();
        $response = $this->chinapay->responseChinapayApi($postData);
        $order_sn = (int)$this->input->post('orderno');
        $result = $this->tourism_order->findByOrderSn($order_sn);
        if ($result->num_rows() <= 0) {
            $this->jsonMessage('订单信息有误，或长时间未支付');
        }
        $orderInfo = $result->row();
        if($orderInfo->order_state != 1 && $orderInfo->order_status != 2){
            $this->jsonMessage('该订单已经支付');
        }
        if($response===true){ // 支付成功
            /*开启事务*/
            $this->db->trans_start();
            $params['order_state'] = 2;
            $params['order_status'] = 3;
            $params['pay_time'] = date('Y-m-d H:i:s');
            $params['pay_bank'] = 1;
            $this->tourism_order->updateStatus($order_sn, $params);
            //更新商品信息
            $product = $this->tourism_order->findTourismGoods($order_sn, true);
            foreach ($product->result() as $item) {
                $product_param['goods_attr_id'] = $item->goods_attr_id;
                $product_param['number'] = $item->number;
                $this->tourism_goods_attr->updateTourismSale($product_param);
            }
            //给供应商发短信，提醒供应商发货
            $tourismOrder = $this->tourism_order->findByOrderId($orderInfo->order_id);
            if( !empty($tourismOrder->pay_swim) ){  //更新U币
                $this->user_account->updateUserAccountUb($tourismOrder->payer_uid,$tourismOrder->pay_swim);
            }
            if (!empty($tourismOrder->cellphone)) {
                //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                $this->sendCommonSmsInfo($tourismOrder->cellphone, 'SMS_136383536', ['providerName' => $tourismOrder->user_name]);
            }
            $this->db->trans_complete();
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_sn, $postdata, $response);
            }
        }
    }
    
    public function isExistOrder($order_sn)
    {
        $result = $this->tourism_order->findByOrderSn($order_sn);
        if ($result->num_rows() <= 0) {
            return false;
        }
        $orderInfo = $result->row();
        if($orderInfo->order_state != 1 && $orderInfo->order_status != 2){
            return false;
        }
        return $orderInfo;
    }
}

